package com.future.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.future.dbutils.TransactionUtils;
import com.future.model.po.DepartmentModel;

public class DepartmentDAO extends BaseDAO<DepartmentModel> {
	private static Logger logger = LogManager.getLogger(DepartmentDAO.class);

	public DepartmentDAO() {

	}

	public DepartmentDAO(Connection conn) {
		super(conn);
	}

	public boolean saveDepartment(DepartmentModel department) {
		String sql = "insert into department (department) values (?)";
		return this.update(sql, department.getDepartment());
	}

	public DepartmentModel findById(Integer id) throws Exception {
		String sql = "select * from department where id = ? ";
		List<DepartmentModel> list = this.searchAsBeanList(sql, DepartmentModel.class, id);
		if (list.size() != 1) {
			throw new Exception("获取部门信息出错");
		}
		return list.get(0);
	}

	public List<DepartmentModel> findAll() {
		String sql = "select * from department ";
		return this.searchAsBeanList(sql, DepartmentModel.class);
	}
	public int findByareaID(Integer id) {
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		StringBuffer sql = new StringBuffer();
		int temp = 0 ;
		sql.append(" select count(*) from   department where id in (select departmentid from user where id in( ")
		.append(" select o.userid from office o where o.userid in (select id from user where areaid = ? )  ")
		.append(" and o.id in (select officeid  from officeservices where issupport=1))) ");
		
		try {
			conn = TransactionUtils.getConnection();
			pst = conn.prepareStatement(sql.toString());
			pst.setInt(1, id);
			rs = pst.executeQuery();
			while (rs!=null&&rs.next()) {
				temp = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(pst!=null){
				try {
					pst.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			TransactionUtils.closeConnection();
		}
		return temp;
	}
}
